﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
using System.Drawing;
using System.Collections;
using SpeechLib;
using Dictionary;

namespace Dictionary
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class MainForm : Window
    {
        bool max;
        string fn,namedict,pathTempImg;
        Button[] btt;
        ArrayList listFileName;
        ArrayList word,history;

        public MainForm()
        {
            InitializeComponent();
        }

#region Function
        private void Init()
        {
            history = new ArrayList();
            BusLayer.LibsContent.CheckDirLib();
            lstWord.Items.Clear();
            max = false;
            this.MaxHeight = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height+7;
            this.MaxWidth = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width+9;
            MaxButtonClick();
            //xoa folder image tam thoi
            pathTempImg = "Temp_9116";
            DataLayer.FileDir.DeleteFolder(BusLayer.LibsContent.GetDirImage() + "\\"+pathTempImg);
            //end
            ReLoadAll();
        }

        //reset lai tat ca cac control, load lai du lieu
        private void ReLoadAll()
        {
            ClearField();
            LoadDicName();
            //effect
            int i = BttDictSlelected();
            if (i >= 0)
                btt[0].Focus();
            BttDictClick();
            if (lstWord.Items.Count > 0)
                lstWord.SelectedIndex = 0;

            history.Clear();
        }

        //Ham tra ve vi tri cua bo tu dien dang duoc chon
        private int BttDictSlelected()
        {
            int i = -1;
            foreach (Button t in btt)
            {
                i++;
            }
            return i;
        }

        //load ten cua cac bo tu dien
        private void LoadDicName()
        {
            listFileName = BusLayer.LibsContent.LoadFileName();
            ArrayList listName = BusLayer.LibsContent.LoadNameDict();
            btt=new Button[listName.Count];
            stkDict.Children.Clear();
            int i = 0;
            foreach (string s in listName)
            {
                btt[i] = new Button();
                btt[i].Content = s;
                btt[i].Click += new RoutedEventHandler(btt_Click);
                stkDict.Children.Add(btt[i]);
                i++;
            }
        }

        //load noi dung cua list Word
        private void LoadListWord()
        {
            word = BusLayer.LibsContent.LoadListWord(fn);
            ClearField();
            foreach (string s in word)
            {
                lstWord.Items.Add(s);
            }
            if (lstWord.Items.Count > 0)
                lstWord.SelectedIndex = 0;
        }

        //Ham handle cua button bo tu dien
        private void BttDictClick()
        {
            history.Clear();
            FadeEffect(rtbContent);
            FadeEffect(lstWord);
            int i = 0;
            foreach (Button b in btt)
            {
                if (b.IsFocused == true)
                {
                    b.IsEnabled = false;
                    fn = listFileName[i].ToString();
                    namedict = b.Content.ToString();
                    LoadListWord();
                }
                else
                {
                    b.IsEnabled = true;
                    i++;
                }
            }
        }

        private void btt_Click(object sender,EventArgs e)
        {
            BttDictClick();
        }

        //ham goi effect cua cac nut min, max, close
        private void ControlButton(System.Windows.Controls.Image i,string s)
        {
            i.RenderTransformOrigin=new System.Windows.Point(0.5,0.5);
            Storyboard stb=new Storyboard();
            stb=(Storyboard)Resources[s];
            i.BeginStoryboard(stb);
        }

        //Khi max button thay doi thuoc tinh
        private void MaxButtonStateChange(string s)
        {
            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.UriSource = new Uri("Image/"+s, UriKind.Relative);
            bi.EndInit();
            ImageSource img = bi;
            imgMax.Source = img;
        }

        //khi user nhan vao max button
        private void MaxButtonClick()
        {
            if (max == true)
                this.WindowState = WindowState.Normal;
            else
                this.WindowState = WindowState.Maximized;
        }
        //Goi hieu ung Scale cho button
        private void ScaleButton(Button btt)
        {
            Storyboard stb = new Storyboard();
            stb = (Storyboard)Resources["ScaleControl"];
            btt.RenderTransformOrigin = new System.Windows.Point(0.5, 0.5);
            btt.BeginStoryboard(stb);
        }

        //Goi hieu ung fade cho richtextbox
        private void FadeEffect(RichTextBox rtb)
        {
            Storyboard stb = new Storyboard();
            stb = (Storyboard)Resources["FadeControl"];
            rtb.RenderTransformOrigin = new System.Windows.Point(0.5, 0.5);
            rtb.BeginStoryboard(stb);
        }

        //Goi hieu ung fade cho listbox
        private void FadeEffect(ListBox ltb)
        {
            Storyboard stb = new Storyboard();
            stb = (Storyboard)Resources["FadeControl"];
            ltb.RenderTransformOrigin = new System.Windows.Point(0.5, 0.5);
            ltb.BeginStoryboard(stb);
        }

        //Xoa noi dung cua cac control
        private void ClearField()
        {
            txtSearchBox.Text = "";
            lstWord.Items.Clear();
            rtbContent.Document.Blocks.Clear();
        }

        //add image vao richtextbox
        private void AddImgToRtb(string folder,string fina)
        {
            try
            {
                Paragraph p = new Paragraph();
                BitmapImage bi=new BitmapImage();
                //Tao image tam thoi
                DataLayer.FileDir.CreateFolder(BusLayer.LibsContent.GetDirImage() + "\\" + pathTempImg);
                DateTime dt = DateTime.Now;
                string n = dt.Year + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Second.ToString()+dt.Millisecond.ToString();
                //MessageBox.Show(n + "===" + dt.Year);
                if (BusLayer.LibsContent.CheckExistImage(pathTempImg, n + System.IO.Path.GetExtension(fina)) == false)
                {
                    BusLayer.ModifyBus.CopyImage(pathTempImg, BusLayer.LibsContent.GetDirImage() + "\\" + folder + "\\" + fina, n);
                    bi = new BitmapImage(new Uri(BusLayer.LibsContent.GetDirImage() + "\\" + pathTempImg + "\\" + n + System.IO.Path.GetExtension(fina), UriKind.Relative));
                }
                //end
                System.Windows.Controls.Image img = new System.Windows.Controls.Image();
                img.Source = bi;
                Figure figure = new Figure();
                figure.Width = new FigureLength(250);
                BlockUIContainer container = new BlockUIContainer(img);
                figure.Blocks.Add(container);
                p.Inlines.Add(figure);
                rtbContent.Document.Blocks.Add(p);
            }
            catch (System.Exception ex)
            {
            }
        }

        //Tim tu trong xml
        private void FindWord(string word)
        {
            ArrayList cnt = BusLayer.LibsContent.LoadContent(fn, word);
            if(cnt==null)
            {
                MessageBox.Show("Không tìm thấy từ \" " + word + " \" !", "EYES - Dictionary");
            }
            else
            {
                history.Add(word);
                rtbContent.Document.Blocks.Clear();
                Paragraph p=new Paragraph();
                //add image
                if(BusLayer.LibsContent.CheckExistImage(System.IO.Path.GetFileNameWithoutExtension(fn),word+".jpg")==true)
                {
                    AddImgToRtb(System.IO.Path.GetFileNameWithoutExtension(fn),word + ".jpg");
                }
                else
                    if (BusLayer.LibsContent.CheckExistImage(System.IO.Path.GetFileNameWithoutExtension(fn),word + ".bmp") == true)
                    {
                        AddImgToRtb(System.IO.Path.GetFileNameWithoutExtension(fn), word + ".bmp");
                    }
                    else
                        if (BusLayer.LibsContent.CheckExistImage(System.IO.Path.GetFileNameWithoutExtension(fn),word + ".png") == true)
                        {
                            AddImgToRtb(System.IO.Path.GetFileNameWithoutExtension(fn), word + ".png");
                        }
                //end
                Run r = new Run(cnt[0].ToString()+"\n");
                r.Foreground = System.Windows.Media.Brushes.Red;
                p = new Paragraph(new Bold(r));
                r = new Run(cnt[1].ToString());
                r.Foreground = System.Windows.Media.Brushes.Blue;
                p.Inlines.Add(r);
                rtbContent.Document.Blocks.Add(p);
                r = new Run(cnt[2].ToString());
                r.Foreground = System.Windows.Media.Brushes.DarkGreen;
                p = new Paragraph(r);
                rtbContent.Document.Blocks.Add(p);
            }
        }

        //Chon tu trong listbox
        private void SelectListWord(string w)
        {
            int i = 0;
            foreach (string wl in lstWord.Items)
            {
                if (string.Compare(w, wl) == 0)
                {
                    lstWord.Focus();
                    lstWord.SelectedIndex = i;
                    return;
                }
                i++;
            }
        }

        //Ham nay duoc goi khi nguoi su dung add, hoac modify thanh cong
        private void AMSucceed(string w)
        {
            LoadListWord();
            SelectListWord(w);
        }

        //tim tu vung trong listbox
        private void SearchWordBox(string st)
        {
            try
            {
                lstWord.Items.Clear();
                txtSearchBox.Foreground = System.Windows.Media.Brushes.White;
                foreach (string w in word)
                {
                    if (w.Length >= st.Length)
                        if (string.Compare(st.ToLower(), w.Substring(0, st.Length).ToLower()) == 0)
                            lstWord.Items.Add(w);
                }
                if (lstWord.Items.Count > 0)
                {
                    lstWord.SelectedIndex = 0;
                }
                else
                {
                    txtSearchBox.Foreground = System.Windows.Media.Brushes.Red;
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
#endregion

        private void imgMin_MouseEnter(object sender, MouseEventArgs e)
        {
            BitmapImage bi=new BitmapImage();
            bi.BeginInit();
            bi.UriSource=new Uri("Image/Minimize_2.png",UriKind.Relative);
            bi.EndInit();
            ImageSource img = bi;
            imgMin.Source=img;
            ControlButton(imgMin,"ControlButton_Down");
        }

        private void imgMin_MouseLeave(object sender, MouseEventArgs e)
        {
            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.UriSource = new Uri("Image/Minimize.png", UriKind.Relative);
            bi.EndInit();
            ImageSource img = bi;
            imgMin.Source = img;
            ControlButton(imgMin,"ControlButton_Up");
        }

        private void imgMax_MouseEnter(object sender, MouseEventArgs e)
        {
            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            if (max == true)
                bi.UriSource = new Uri("Image/Max_2.png", UriKind.Relative);
            else
                bi.UriSource = new Uri("Image/Maximize_2.png", UriKind.Relative);
            bi.EndInit();
            ImageSource img = bi;
            imgMax.Source = img;
            ControlButton(imgMax, "ControlButton_Down");
        }

        private void imgMax_MouseLeave(object sender, MouseEventArgs e)
        {
            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            if(max==true)
                bi.UriSource = new Uri("Image/Max.png", UriKind.Relative);
            else
                bi.UriSource = new Uri("Image/Maximize.png", UriKind.Relative);
            bi.EndInit();
            ImageSource img = bi;
            imgMax.Source = img;
            ControlButton(imgMax, "ControlButton_Up");
        }

        private void imgClose_MouseEnter(object sender, MouseEventArgs e)
        {
            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.UriSource = new Uri("Image/Close_2.png", UriKind.Relative);
            bi.EndInit();
            ImageSource img = bi;
            imgClose.Source = img;
            ControlButton(imgClose, "ControlButton_Down");
        }

        private void imgClose_MouseLeave(object sender, MouseEventArgs e)
        {
            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.UriSource = new Uri("Image/Close.png", UriKind.Relative);
            bi.EndInit();
            ImageSource img = bi;
            imgClose.Source = img;
            ControlButton(imgClose, "ControlButton_Up");
        }

        private void FrmMain_StateChanged(object sender, EventArgs e)
        {
            if (this.WindowState==WindowState.Maximized)
            {
                max=true;
                MaxButtonStateChange("Max.png");
                imgMax.ToolTip = "Restore Down";
            }
            else
            {
                max=false;
                MaxButtonStateChange("Maximize.png");
                imgMax.ToolTip = "Maximize";
            }
        }

        private void imgMin_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void imgMax_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            MaxButtonClick();
        }

        private void imgClose_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Close();
        }

        private void lblTitle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void txtSearchBox_MouseEnter(object sender, MouseEventArgs e)
        {
            Storyboard stb = new Storyboard();
            stb = (Storyboard)Resources["ScaleControl"];
            txtSearchBox.RenderTransformOrigin = new System.Windows.Point(0.5, 0.5);
            txtSearchBox.BeginStoryboard(stb);
        }

        private void FrmMain_Loaded(object sender, RoutedEventArgs e)
        {
            Init();
        }

        private void bttAdd_MouseEnter(object sender, MouseEventArgs e)
        {
            ScaleButton(bttAdd);
        }

        private void bttModify_MouseEnter(object sender, MouseEventArgs e)
        {
            ScaleButton(bttModify);
        }

        private void bttDelete_MouseEnter(object sender, MouseEventArgs e)
        {
            ScaleButton(bttDelete);
        }

        private void bttGoogle_MouseEnter(object sender, MouseEventArgs e)
        {
            ScaleButton(bttGoogle);
        }

        private void bttAddDict_MouseEnter(object sender, MouseEventArgs e)
        {
            ScaleButton(bttAddDict);
        }

        private void bttDelDict_MouseEnter(object sender, MouseEventArgs e)
        {
            ScaleButton(bttDelDict);
        }

        private void BttSound_MouseEnter(object sender, MouseEventArgs e)
        {
            ScaleButton(BttSound);
        }

        private void lstWord_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lstWord.SelectedItem != null)
            {
                FindWord(lstWord.SelectedItem.ToString());
                if (txtSearchBox.IsFocused== false)
                    txtSearchBox.Text = lstWord.SelectedItem.ToString();
            }
        }

        private void BttSound_Click(object sender, RoutedEventArgs e)
        {
            if (lstWord.SelectedItem != null)
            {
                SpVoice voice = new SpVoice();
                voice.Voice = voice.GetVoices("", "").Item(0);
                voice.Speak(lstWord.SelectedItem.ToString(), SpeechVoiceSpeakFlags.SVSFDefault);
            }
        }

        private void bttAdd_Click(object sender, RoutedEventArgs e)
        {
            if (btt.Length <= 0)
                return;

            PresentationLayer.Word fw = new PresentationLayer.Word("ADD",fn);
            fw.ShowDialog();
            string ok=fw.GetOk();
            if (ok != null)
            {
                AMSucceed(ok);
            }
        }

        private void bttModify_Click(object sender, RoutedEventArgs e)
        {
            if (lstWord.SelectedItem != null)
            {
                PresentationLayer.Word fw = new PresentationLayer.Word("MODIFY", fn, lstWord.SelectedItem.ToString());
                fw.ShowDialog();
                string ok = fw.GetOk();
                if (ok != null)
                {
                    AMSucceed(ok);
                }
            }
        }

        private void bttDelete_Click(object sender, RoutedEventArgs e)
        {
            if (lstWord.SelectedItem != null)
            {
                if (System.Windows.Forms.MessageBox.Show("Bạn có chắc chắn muốn xóa từ \" " + lstWord.SelectedItem.ToString() + " \" không?", "Xóa Từ", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    BusLayer.ModifyBus.DeleteWord(fn,lstWord.SelectedItem.ToString());
                    // delete file anh, neu co
                    if (BusLayer.LibsContent.CheckExistImage(System.IO.Path.GetFileNameWithoutExtension(fn), lstWord.SelectedItem.ToString() + ".jpg") == true)
                    {
                        DataLayer.FileDir.DeleteFile(BusLayer.LibsContent.GetDirImage() + "\\" + System.IO.Path.GetFileNameWithoutExtension(fn) + "\\" + lstWord.SelectedItem.ToString() + ".jpg");
                    }
                    else
                        if (BusLayer.LibsContent.CheckExistImage(System.IO.Path.GetFileNameWithoutExtension(fn), lstWord.SelectedItem.ToString() + ".bmp") == true)
                        {
                            DataLayer.FileDir.DeleteFile(BusLayer.LibsContent.GetDirImage() + "\\" + System.IO.Path.GetFileNameWithoutExtension(fn) + "\\" + lstWord.SelectedItem.ToString() + ".bmp");
                        }
                        else
                            if (BusLayer.LibsContent.CheckExistImage(System.IO.Path.GetFileNameWithoutExtension(fn), lstWord.SelectedItem.ToString() + ".png") == true)
                            {
                                DataLayer.FileDir.DeleteFile(BusLayer.LibsContent.GetDirImage() + "\\" + System.IO.Path.GetFileNameWithoutExtension(fn) + "\\" + lstWord.SelectedItem.ToString() + ".png");
                            }
                    //chon tu moi khi da xoa tu cu
                    //clear search box & richtextbox
                    txtSearchBox.Text = "";
                    rtbContent.Document.Blocks.Clear();
                    //end
                    int i = lstWord.SelectedIndex;
                    lstWord.Items.RemoveAt(lstWord.SelectedIndex);
                    if (i<lstWord.Items.Count)
                        lstWord.SelectedIndex=i;
                    else
                        if ((lstWord.Items.Count>0)&&(i>=lstWord.Items.Count))
                            lstWord.SelectedIndex = i-1;
                }
            }
        }

        private void txtSearchBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (txtSearchBox.IsFocused== true)
                SearchWordBox(txtSearchBox.Text);
        }

        private void lstWord_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if ((lstWord.SelectedItem != null) && (txtSearchBox.IsFocused == false))
                txtSearchBox.Text = lstWord.SelectedItem.ToString();
        }

        private void bttAddDict_Click(object sender, RoutedEventArgs e)
        {
            PresentationLayer.Dict fd = new PresentationLayer.Dict();
            fd.ShowDialog();
            if (fd.ok != null)
            {
                ReLoadAll();
                int i = 0;
                foreach (string s in listFileName)
                {
                    if (string.Compare(s.ToLower(), fd.ok.ToLower()) == 0)
                    {
                        btt[i].Focus();
                        BttDictClick();
                    }
                    else
                        i++;
                }
            }
        }

        private void bttDelDict_Click(object sender, RoutedEventArgs e)
        {
            if (btt.Length <= 0)
                return;

            if (System.Windows.Forms.MessageBox.Show("Bạn có chắc chắn muốn xóa bộ từ điển \" " + namedict + " \" không?", "Xóa Bộ Từ Điển", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                if (BusLayer.ModifyDictBus.DeleteDict(fn) == false)
                {
                    MessageBox.Show("Không thể xóa bộ từ điển này !", "Xóa Bộ Từ Điển");
                    return;
                }
                else
                {
                    ReLoadAll();
                }
            }
        }

        private void bttGoogle_Click(object sender, RoutedEventArgs e)
        {
            PresentationLayer.Translator ft = new PresentationLayer.Translator();
            ft.ShowDialog();
        }

        private void bttAbout_MouseEnter(object sender, MouseEventArgs e)
        {
            ScaleButton(bttAbout);
        }

        private void bttAbout_Click(object sender, RoutedEventArgs e)
        {
            PresentationLayer.About fa = new PresentationLayer.About();
            fa.ShowDialog();
        }

        private void bttThongKe_Click(object sender, RoutedEventArgs e)
        {
            if (btt.Length <= 0)
                return;

            PresentationLayer.ThongKe ftk = new PresentationLayer.ThongKe(namedict,lstWord.Items.Count,history);
            ftk.ShowDialog();
        }
    }
}
